/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.volatileengine.material.xml;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.volatileengine.VolatileEngineException;
import com.volatileengine.material.Pass;
import com.volatileengine.material.SceneMaterial;
import com.volatileengine.xml.IFileLoader;
import com.volatileengine.xml.XMLLoader;
import com.volatileengine.xml.XMLParsingException;
import com.volatileengine.xml.elements.Element;
import com.volatileengine.xml.elements.ResourceXMLElement;
import com.volatileengine.xml.elements.SimpleXMLElement;

/**
 * 
 * @author Administrator
 */
public class SceneMaterialXMLElement extends SimpleXMLElement<SceneMaterial> {

	private List<Pass> passList;

	public String getAssociatedTag() {
		return "scenematerial";
	}

	public Element<?> instantiateChild(String tagName, IFileLoader<?> loader) {
		if ("pass".equalsIgnoreCase(tagName)) {
			return new PassXMLElement();
		} else if ("resource".equalsIgnoreCase(tagName)) {
			return new ResourceXMLElement();
		}
		throw new XMLParsingException(getAssociatedTag() + " does not have " + tagName + " as a child");
	}

	public void processChild(Element<?> child, IFileLoader<?> loader) {
		if ("pass".equalsIgnoreCase(child.getAssociatedTag())) {
			if (passList == null) {
				passList = new ArrayList<Pass>();
			}
			passList.add(((PassXMLElement) child).getValue());
		} else if ("resource".equalsIgnoreCase(child.getAssociatedTag())) {
			try {
				IFileLoader<SceneMaterial> nloader = new XMLLoader<SceneMaterial>(new SceneMaterialXMLElement());
				nloader.setResourceFinder(loader.getResourceFinder());
				this.value = nloader.load((String) child.getValue(), null);
			} catch (IOException ex) {
				throw new VolatileEngineException(ex);
			}
		}
	}

	public void endElement(IFileLoader<?> loader) {
		if (value == null) {
			value = new SceneMaterial();
			if (passList == null) {
				throw new XMLParsingException("SceneMatrial must declare atleast 1 Pass");
			}
			value.getPasses().addAll(passList);
		}
	}
}
